package com.oliet.util;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.UUID;

/**
 * @author jiaZhenpeng
 * @Title: JwtUtils
 * @Package com.oliet.util
 * @Description: JWT工具类
 * @date 2023-11-28 11:40
 */
@Data
@Component
@ConfigurationProperties(prefix = "oliet.jwt")
public class JwtUtils {

    /**
     * 过期时间
     */
    private Long expire;
    /**
     * 密钥
     */
    private String secret;
    /**
     * 头部
     */
    private String header;

    // 生成JWT
    public String generateToken(String username, Object userData) {

        Date nowDate = new Date();
        Date expireDate = new Date(nowDate.getTime() + 1000 * expire);

        String code = null;
        String fullName = null;
        if (ObjectUtil.isNotNull(userData)) {
            code = BeanUtil.beanToMap(userData).get("code") + "";
            fullName = BeanUtil.beanToMap(userData).get("fullName") + "";
        }


        return Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setSubject(username)
                .claim("code", code)
                .claim("fullName", fullName)
                .setIssuedAt(nowDate)
                .setExpiration(expireDate)    // 7天过期
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    // 解析JWT
    public Claims getClaimsByToken(String jwt) {
        try {
            return Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(jwt)
                    .getBody();
        } catch (Exception e) {
            return null;
        }
    }

    // 判断JWT是否过期
    public boolean isTokenExpired(Claims claims) {
        return claims.getExpiration().before(new Date());
    }


    public static void main(String[] args) {
        System.out.println("生成的密钥： " + UUID.randomUUID().toString().replace("-", ""));
    }

}
